package com.xyzwps.demo.springbootreactive;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.netty.http.client.HttpClient;

import java.nio.charset.StandardCharsets;
import java.time.Duration;

@RestController
@RequestMapping("/reactor")
public class ReactorController {

    @GetMapping("/delay/{sec}")
    public Mono<Integer> delay(@PathVariable("sec") int seconds) {
        return Mono.just(seconds).delayElement(Duration.ofSeconds(seconds));
    }

    static HttpClient httpClient = HttpClient.create();

    static Mono<Integer> callDelay(int sec) {
        return httpClient
                .get().uri("http://localhost:8080/delay/" + sec)
                .responseSingle((res, content) -> content.asString(StandardCharsets.UTF_8))
                .map(Integer::parseInt);
    }

    /**
     * 看 flatMap 里各位是并行还是串行
     */
    @GetMapping("/flat-map")
    public Mono<String> seeFlatMapParallelism() {
        long ts = System.currentTimeMillis();
        return Flux.range(1, 8)
                .flatMap(ReactorController::callDelay)
                .reduce(0, Integer::sum)
                .map(it -> String.format("sum=%d, ts=%dms", it, System.currentTimeMillis() - ts));
    }
}
